package dhm.com.hpx.activity;

        import android.annotation.SuppressLint;
        import android.content.Intent;
        import android.graphics.Color;
        import android.os.Build;
        import android.support.design.widget.TabLayout;
        import android.support.v4.app.Fragment;
        import android.support.v4.view.ViewPager;
        import android.view.KeyEvent;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.widget.ImageView;
        import android.widget.LinearLayout;
        import android.widget.TextView;
        import android.widget.Toast;

        import com.stx.xhb.xbanner.XBanner;

        import java.text.SimpleDateFormat;
        import java.util.ArrayList;
        import java.util.Date;
        import java.util.HashMap;
        import java.util.Map;

        import butterknife.BindView;
        import butterknife.ButterKnife;
        import dhm.com.hpx.adapter.MainVpFgAdapter;
        import dhm.com.hpx.R;
        import dhm.com.hpx.base.BaseActivity;
        import dhm.com.hpx.base.Presenter.PressenterImpl;
        import dhm.com.hpx.base.netWork.Constant;
        import dhm.com.hpx.base.netWork.LoginContract;
        import dhm.com.hpx.entity.GetUserInfoBean;
        import dhm.com.hpx.fragment.MainFragment;
        import dhm.com.hpx.fragment.MessageFragment;
        import dhm.com.hpx.fragment.MineFragment;
        import dhm.com.hpx.utils.SpUtils;

public class MainActivity extends BaseActivity implements LoginContract.IView{

    @BindView(R.id.main_vp)
    ViewPager mMainVp;
    @BindView(R.id.banner)
    XBanner banner;
    @BindView(R.id.main_tablayout)
    TabLayout mMainTablayout;
    @BindView(R.id.main_container)
    LinearLayout mainContainer;
    private MainFragment mainFragment;
    private MessageFragment messageFragment;
    private MineFragment mineFragment;
    private MainVpFgAdapter mainVpFgAdapter;
    private ArrayList<String> titles;
    private ArrayList<Fragment> fragments;
    private String uid;
    private PressenterImpl pressenter;

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        ButterKnife.bind(this);
        pressenter = new PressenterImpl();
        pressenter.attachView(this);
        getWindow().setStatusBarColor(getResources().getColor(R.color.main));

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
//            getWindow().getDecorView().setSystemUiVisibility(View.);

            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    |View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
            decorView.setSystemUiVisibility(uiOptions);


        }
        mMainTablayout.setSelectedTabIndicatorHeight(0);
        //创建tab
        titles = new ArrayList<>();
        titles.add("首页");
        titles.add("消息");
        titles.add("我的");

        //四个fragments
        fragments = new ArrayList<>();
        mainFragment=new MainFragment();
        messageFragment=new MessageFragment();
        mineFragment = new MineFragment();
        fragments.add(mainFragment);
        fragments.add(messageFragment);
        fragments.add(mineFragment);

        //设置适配器
        mainVpFgAdapter = new MainVpFgAdapter(getSupportFragmentManager(), fragments, titles);

        //绑定适配器
        mMainVp.setAdapter(mainVpFgAdapter);
        mMainVp.setOffscreenPageLimit(0);
        //设置联动
        mMainTablayout.setupWithViewPager(mMainVp);

        setupTabIcons();//设置底部TabLayout的item

        mMainTablayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @SuppressLint("NewApi")
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();

                switch (position) {
                    case 0:
                        getWindow().setStatusBarColor(getResources().getColor(R.color.main));

                        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
//                            getWindow().getDecorView().setSystemUiVisibility(View.);

                            View decorView = getWindow().getDecorView();
                            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                    |View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
                            decorView.setSystemUiVisibility(uiOptions);

                        }
                        break;
                    case 1:
                        getWindow().setStatusBarColor(Color.WHITE);
                        //状态栏中的文字颜色和图标颜色，需要android系统6.0以上，而且目前只有一种可以修改（一种是深色，一种是浅色即白色）
                        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
//                            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

                            View decorView = getWindow().getDecorView();
                            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                    |View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
                            decorView.setSystemUiVisibility(uiOptions);

                        }
                        break;
                    case 2:
                        getWindow().setStatusBarColor(getResources().getColor(R.color.main));

                        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
//                            getWindow().getDecorView().setSystemUiVisibility(View.);

                            View decorView = getWindow().getDecorView();
                            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                    |View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
                            decorView.setSystemUiVisibility(uiOptions);

                        }

                        break;
                    default:
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


        uid = SpUtils.getString(MainActivity.this, "uid");
        if (uid == null || uid.equals("")) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            MainActivity.this.startActivity(intent);
            MainActivity.this.finish();
        }else {
            Map<String,String> map=new HashMap<>();
            map.put("token", Constant.TOKEN);
            map.put("uid",uid);
            pressenter.sendMessage(MainActivity.this,Constant.get_userinfo,map, GetUserInfoBean.class);
        }


       /* if (!FcfrtAppBhUtils.isIgnoringBatteryOptimizations(this)){
            FcfrtAppBhUtils.requestIgnoreBatteryOptimizations(this);
        }*/

    }


    /**
     * 判断2个时间大小
     * yyyy-MM-dd HH:mm 格式（自己可以修改成想要的时间格式）
     * @param startTime
     * @param endTime
     * @return
     */
    public String timeCompare(String startTime, String endTime){
        int i=0;
        //注意：传过来的时间格式必须要和这里填入的时间格式相同
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime()<date1.getTime()){
                //没过期
                i= 1;
            }else if (date2.getTime()==date1.getTime()){
                //过期
                Toast.makeText(MainActivity.this, "会员已过期", Toast.LENGTH_SHORT).show();
                i= 2;
            }else if (date2.getTime()>date1.getTime()){
                //过期
                Toast.makeText(MainActivity.this, "会员已过期", Toast.LENGTH_SHORT).show();
                i= 3;
            }
        } catch (Exception e) {

        }

        return  i+"";
    }




    @Override
    protected void initData() {

        stateNetWork();

    }

    //有几个底部的item就写几个
    private void setupTabIcons() {
        //tablayout图文效果
        for (int i = 0; i < fragments.size(); i++) {
            mMainTablayout.getTabAt(i).setCustomView(getView(i));
        }
    }

    @SuppressLint("NewApi")
    private View getView(int position) {
        View tabitem = LayoutInflater.from(this).inflate(R.layout.tabitem, null);
        ImageView iv = (ImageView) tabitem.findViewById(R.id.tabiv);
        TextView tv = (TextView) tabitem.findViewById(R.id.tabtv);
        tv.setText(titles.get(position));
        ArrayList<Integer> images = new ArrayList<>();
        images.add(R.drawable.selector_main);
        images.add(R.drawable.selector_message);
        images.add(R.drawable.selector_mine);
        iv.setImageResource(images.get(position));
        return tabitem;
    }


    /**
     * 防止误触退出
     */
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();

            } else {
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void requesta(Object data) {
        if (data instanceof GetUserInfoBean) {
            GetUserInfoBean getUserInfoBean = (GetUserInfoBean) data;
            if (getUserInfoBean.getCode() == 1) {
                SpUtils.saveString(MainActivity.this, "phone", getUserInfoBean.getData().getMobile());
            }
        }
    }

    @Override
    public void fail(String error) {

    }
}
